<?php

$DS = DIRECTORY_SEPARATOR;

$f = @$_GET['f'];
$w = @$_GET['w'];
$h = @$_GET['h'];
$force = @$_GET['force'];

$base = dirname(__FILE__);
$path = $base . $DS . $f;
$filename = pathinfo($path, PATHINFO_FILENAME);
$ext  = strtolower(pathinfo($path, PATHINFO_EXTENSION));
$type = $ext=='jpg' ? 'jpeg' : $ext;

if (! file_exists($path)) {
    $path = $base . $DS . 'no-image.png';
}

$img = new Image($path);

if (isset($w) || isset($h)) {
    $img->resize($w, $h, $force);
}

$img->setImageFormat($type);
header("Content-Type: image/{$type}");
header("Content-Disposition: inline; filename={$filename}.{$ext}");
echo $img;

class Image extends Imagick {

    private $path;
    private $type;

    public function __construct($path) {
        $this->path = $path;
        parent::__construct($path);
        
        $this->type = strtolower(substr($path, strrpos($path, '.') + 1));
    }
    
    public function setOutput() {
        header('Content-Type: image/' . $this->type);
    }
    
    public function resize($w=null, $h=null, $force=false) {
        $wOriginal = $this->getImageWidth();
        $hOriginal = $this->getImageHeight();

        $w1 = $wOriginal;
        $h1 = $hOriginal;
        
        if ($w > 0) {
            $h1 = $hOriginal * $w / $wOriginal;
            $w1 = $w;
        }
        
        if ($h>0) {
            if ($force) {
                $h1 = $h;
            } elseif($h<$h1) {
                $w1 = $wOriginal * $h / $hOriginal;
                $h1 = $h;
            }
        }
        
        $this->thumbnailimage($w1, $h1);
    }
}

?>
